/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.weso.acota.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;

/**
 *
 * @author chema
 */
public class StringUtils {

            //Helper Method
    /*
         public static List jsonArray2List(JSONArray array) throws JSONException {
            List l = new ArrayList(array.length());
             for (int i = 0; i < array.length(); i++) {
                 if (array.get(i) instanceof JSONArray) {
                     l.add(jsonArray2List((JSONArray) array.get(i)));
                } else {
                     l.add(array.get(i));
                }
            }
            return l;
        }
     * */


   public static String Document2StringFormat(Document doc, String xsl){
        StringWriter strWriter = new StringWriter();
        try{
        XMLSerializer serializer = null;
        serializer = new XMLSerializer();
        serializer.processingInstruction("xml-stylesheet", xsl);
        serializer.setOutputCharStream(strWriter);
		serializer.serialize(doc);
		serializer.setNamespaces(true);
		strWriter.close();
		} catch (Exception e) {
			return "";
		}
        return  strWriter.toString();

    }

        
public static String slurp (InputStream in) throws IOException {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        out.append(new String(b, 0, n));
    }
    return out.toString();
}

public static String replace(String source, String pattern, String replace)
	{
		if (source!=null)
		{
			final int len = pattern.length();
			StringBuffer sb = new StringBuffer();
			int found = -1;
			int start = 0;

			while( (found = source.indexOf(pattern, start) ) != -1) {
				sb.append(source.substring(start, found));
				sb.append(replace);
				start = found + len;
			}

			sb.append(source.substring(start));

			return sb.toString();
		}
		else return "";
	}



}
